package com.nhc.activity_fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.astrob.activitys.AppContext;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.astrob.util.Utils;
import com.astrob.view.BaseViewHolder;
import com.nhc.database.manager.IECenter;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.model.Entry;
import zuo.biao.library.ui.PageScroller;

public class MapDirListActivity extends BaseActivity implements View.OnClickListener {
    private final String TAG = "MapDirListActivity";

    //启动方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    /**
     * 启动这个Activity的Intent
     *
     * @param context
     * @return
     */
    public static Intent createIntent(Context context) {
        return new Intent(context, MapDirListActivity.class);
    }

    //启动方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mapdirlist_activity);

        //功能归类分区方法，必须调用<<<<<<<<<<
        initView();
        initData();
        initEvent();
        //功能归类分区方法，必须调用>>>>>>>>>>

    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private ListView lv_all;

    @Override
    public void initView() {//必须调用
        lv_all = (ListView) findViewById(R.id.lv_all);
    }

    //UI显示区(操作UI，但不存在数据获取或处理代码，也不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    private void setList(List<Entry<Integer, String>> list) {
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lv_all.setAdapter(adapter);
        }
        adapter.refresh(list);
    }

    private List<Entry<Integer, String>> maplist;

    //示例代码>>>>>>>>>
    @Override
    public void initData() {//必须调用

        if (SysUtils.getInstance().mapsource == 1001) {
            _mapfilepath = SysUtils.getInstance().mapfilepath1;
        } else if (SysUtils.getInstance().mapsource == 1002) {
            _mapfilepath = SysUtils.getInstance().mapfilepath2;
        } else if (SysUtils.getInstance().mapsource == 1003) {
            _mapfilepath = SysUtils.getInstance().mapfilepath3;
        } else if (SysUtils.getInstance().mapsource == 1004) {
            _mapfilepath = SysUtils.getInstance().mapfilepath4;
        }

        showProgressDialog(R.string.loading);
        runThread(TAG + "initData", new Runnable() {
            @Override
            public void run() {
                resetAlldata();
                runUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dismissProgressDialog();
                        setList();
                    }
                });
            }
        });
    }

    //Data数据区(存在数据获取或处理代码，但不存在事件监听代码)>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    //Event事件区(只要存在事件监听代码就是)<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    @Override
    public void initEvent() {//必须在onCreate方法内调用
        //示例代码<<<<<<<<<<<<<<<<<<<
        lv_all.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                boolean isSelected = hashMap.get(position);
//                for (int i = 0; i < filelist.size(); i++) {
//                    hashMap.put(i, !isSelected);
//                }

                //修改为单选
                for (int i = 0; i < filelist.size(); i++) {
                    if (i == position) {
                        hashMap.put(i, true);
                    } else {
                        hashMap.put(i, false);
                    }
                }

                if (adapter != null) {
                    adapter.notifyDataSetChanged();
                }
            }
        });

        //分页滚动示例代码<<<<<<<<<<<<<<<<<<<
        new PageScroller(lv_all).init();
        //分页滚动示例代码>>>>>>>>>>>>>>>>>>>

        //示例代码>>>>>>>>>>>>>>>>>>>
    }

    //系统自带监听方法<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

    String _mapfilepath = "";

    @Override
    public void finish() {
        _mapfilepath = "";
        for (int i = 0; i < filelist.size(); i++) {
            if (hashMap.get(i)) {
                String filePath = filelist.get(i).getValue();
                _mapfilepath += filePath;
            }
        }

        if (_mapfilepath.length() < 1 && filelist.size() > 0) {
            //至少有个文件
            _mapfilepath = filelist.get(0).getValue();
        }

        if (SysUtils.getInstance().mapsource == 1001) {
            SysUtils.getInstance().mapfilepath1 = _mapfilepath;
            SysUtils.getInstance().mapsforgeFile = new File(SysUtils.getInstance().mapfilepath1);
        } else if (SysUtils.getInstance().mapsource == 1002) {
            SysUtils.getInstance().mapfilepath2 = _mapfilepath;
        } else if (SysUtils.getInstance().mapsource == 1003) {
            SysUtils.getInstance().mapfilepath3 = _mapfilepath;
        } else if (SysUtils.getInstance().mapsource == 1004) {
            SysUtils.getInstance().mapfilepath4 = _mapfilepath;
        }

        SysUtils.getInstance().saveMapSource();

        if (SysUtils.getInstance().mapsource == 1001) {
            //mapsforge 重新加载file
            SysUtils.getInstance().loadeMapSource();
        }

        super.finish();
    }

    private String _strSuffix = "";
    //SD卡 -- /mnt/sdcard2/
    //类相关监听<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    //只加载一个文件，不分类型
    private void resetAlldata() {
        filelist = new ArrayList<Entry<Integer, String>>();
        filenamelist = new ArrayList<String>();
        if (SysUtils.getInstance().mapsource == 1001) {
            _strSuffix = ".map";
            //BHCMapper/mapsforge
            String EXDIR0 = Start.RUNDIR + "/mapsforge/";
            String EXDIR1 = "/mnt/sdcard2/BHCMapper/mapsforge/";
            seachFile(EXDIR0);
            seachFile(EXDIR1);
        } else if (SysUtils.getInstance().mapsource >= 1002) {
//            _strSuffix = ".gemf";
            String EXDIR0 = Start.RUNDIR + "/offline/";
            String EXDIR1 = "/mnt/sdcard2/BHCMapper/offline/";
            seachFile(EXDIR0);
            seachFile(EXDIR1);
        }

        if (_mapfilepath.length() < 1 && filelist.size() > 0) {
            //至少有个文件
            _mapfilepath = filelist.get(0).getValue();
        }

        List<String> namelist = new ArrayList<String>();
        String[] strFiles = _mapfilepath.split(";");
        if (strFiles != null || strFiles.length < 1) {
            for (int i = 0; i < strFiles.length; i++) {
                namelist.add(strFiles[i]);
            }
        }

        boolean isSelected = false;
        if (hashMap == null) {
            hashMap = new HashMap<Integer, Boolean>();
        }
        hashMap.clear();
        for (int i = 0; i < filelist.size(); i++) {
            isSelected = false;
            if (namelist.contains(filelist.get(i).getValue())) {
                isSelected = true;
            }
            hashMap.put(i, isSelected);
        }
    }

    //原方案，可以加载多个文件
    private void resetAlldata2() {
        filelist = new ArrayList<Entry<Integer, String>>();
        filenamelist = new ArrayList<String>();
        if (SysUtils.getInstance().mapsource == 1001) {
            _strSuffix = ".map";
            //BHCMapper/mapsforge
            String EXDIR0 = Start.RUNDIR + "/mapsforge/";
            String EXDIR1 = "/mnt/sdcard2/BHCMapper/mapsforge/";
            seachFile(EXDIR0);
            seachFile(EXDIR1);
        } else if (SysUtils.getInstance().mapsource == 1002) {
            _strSuffix = ".gemf";
            String EXDIR0 = Start.RUNDIR + "/offline/";
            String EXDIR1 = "/mnt/sdcard2/BHCMapper/offline/";
            seachFile(EXDIR0);
            seachFile(EXDIR1);
        } else if (SysUtils.getInstance().mapsource == 1003) {
            _strSuffix = ".mbtiles";
            String EXDIR0 = Start.RUNDIR + "/offline/";
            String EXDIR1 = "/mnt/sdcard2/BHCMapper/offline/";
            seachFile(EXDIR0);
            seachFile(EXDIR1);
        } else if (SysUtils.getInstance().mapsource == 1004) {
            _strSuffix = ".zip";
            String EXDIR0 = Start.RUNDIR + "/offline/";
            String EXDIR1 = "/mnt/sdcard2/BHCMapper/offline/";
            seachFile(EXDIR0);
            seachFile(EXDIR1);
        }

        if (_mapfilepath.length() < 1 && filelist.size() > 0) {
            //至少有个文件
            _mapfilepath = filelist.get(0).getValue();
        }

        List<String> namelist = new ArrayList<String>();
        String[] strFiles = _mapfilepath.split(";");
        if (strFiles != null || strFiles.length < 1) {
            for (int i = 0; i < strFiles.length; i++) {
                namelist.add(strFiles[i]);
            }
        }

        boolean isSelected = false;
        if (hashMap == null) {
            hashMap = new HashMap<Integer, Boolean>();
        }
        hashMap.clear();
        for (int i = 0; i < filelist.size(); i++) {
            isSelected = false;
            if (namelist.contains(filelist.get(i).getValue())) {
                isSelected = true;
            }
            hashMap.put(i, isSelected);
        }
    }

    int _num = 0;

    //同名的地图只加载一个
    private void seachFile(String path) {
        File fRoot = new File(path);
        File[] files = fRoot.listFiles();
        if (files == null)
            return;

        for (int j = 0; j < files.length; j++) {
            String fName = files[j].getName();
            if (filenamelist.contains(fName)) {
                continue;
            }
            if (files[j].isDirectory()) {
                seachFile(files[j].getPath());
            } else {
                if (_strSuffix.length() < 1) {
                    if (fName.contains("-journal")) {
                        continue;
                    }
                    if (fName.contains(".gemf") || fName.contains(".mbtiles") || fName.contains(".zip") || fName.contains(".sqlite")) {
                        filelist.add(new Entry<Integer, String>(_num, files[j].getPath()));
                        filenamelist.add(fName);
                        _num++;
                    }
                } else {
                    //mapsforge  *.map
                    if (fName.contains(_strSuffix)) {
                        filelist.add(new Entry<Integer, String>(_num, files[j].getPath()));
                        filenamelist.add(fName);
                        _num++;
                    }
                }
            }
        }
    }

    private List<String> filenamelist;
    private List<Entry<Integer, String>> filelist;
    private HashMap<Integer, Boolean> hashMap;

    //示例代码<<<<<<<<
    private DemoAdapter adapter;
    //示例代码>>>>>>>>

    /**
     * 示例方法 ：显示列表内容
     */
    private void setList() {
        if (adapter == null) {
            adapter = new DemoAdapter(context);
            lv_all.setAdapter(adapter);
        }
        adapter.refresh(filelist);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }

    //类相关监听>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

    //系统自带监听方法>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>


    public class DemoAdapter extends BaseAdapter<Entry<Integer, String>> {
        public DemoAdapter(Activity context) {
            super(context);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.mapdiritem_view, parent, false);
            }

            TextView iv_check = BaseViewHolder.get(convertView, R.id.iv_check);
            TextView tv_mapname = BaseViewHolder.get(convertView, R.id.tv_mapname);
            iv_check.setTypeface(AppContext.getInstances().getIconfont());

            final Entry<Integer, String> data = getItem(position);
            tv_mapname.setText(data.getValue());

            boolean isSelected = false;
            isSelected = hashMap.get(position);

            if (isSelected) {
                iv_check.setText(R.string.fonticon_xz);
            } else {
                iv_check.setText(R.string.fonticon_wxz);
            }

            return super.getView(position, convertView, parent);
        }
    }


}
